//
//  BaseTabbarController.m
//  YOBO
//
//  Created by 王根强 on 2017/3/9.
//  Copyright © 2017年 walemaishan. All rights reserved.
//


#import "BaseTabbarController.h"
#import "BaseNavigationController.h"

#import "MHomeViewController.h"
#import "MControlViewController.h"
#import "MDataCompartmentViewController.h"
#import "MTaobaoViewController.h"
//#import "YOPushLiveViewController.h"
//#import "YOFirstLiveViewController.h"
//#import "DeviceDetailsViewController.h"


@interface BaseTabbarController ()<UITabBarControllerDelegate>
@property (nonatomic, strong) UIButton *tabBarButton;
@end

@implementation BaseTabbarController
@synthesize tabBarButton;

#pragma mark- setup
- (void)setUp {
    //添加突出按钮
    [self addCenterButtonWithImage:[UIImage imageNamed:@"bg_tabbar_live_normal"] selectedImage:[UIImage imageNamed:@"bg_tabbar_live_normal"]];
    //UITabBarControllerDelegate 指定为自己
    self.delegate = self;
    //指定当前页——中间页
    self.selectedIndex = 0;
}

#pragma mark - addCenterButton
- (void)addCenterButtonWithImage:(UIImage*)buttonImage selectedImage:(UIImage*)selectedImage {
    tabBarButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [tabBarButton addTarget:self action:@selector(pressChange:) forControlEvents:UIControlEventTouchUpInside];
    tabBarButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;
    
    //设定button大小为适应图片
    tabBarButton.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height);
    [tabBarButton setImage:buttonImage forState:UIControlStateNormal];
    [tabBarButton setImage:selectedImage forState:UIControlStateSelected];
    
    tabBarButton.centerX = self.tabBar.centerX;
    //调整中间按钮的中线点Y值
    tabBarButton.centerY = self.tabBar.height / 4;
    
    //去掉选中button时候的阴影
    //button.adjustsImageWhenHighlighted = NO;
    [self.tabBar addSubview:tabBarButton];
}

- (void)pressChange:(id)sender {
//    if ([YONetwork isNetWorkConnecting] == YES) {
//        self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//        NSMutableDictionary * postDic = [[NSMutableDictionary alloc] init];
//        [postDic setObject:[UserConfig shareInstance]._appUserID forKey:@"userId"];
//        NSString * url = [NSString stringWithFormat:@"%@%@",PRODUCTION_BASE_URL, API_REQUEST_PRELIVE];
//        [YONetwork postWithURL:url withParams:postDic withSuccessBlock:^(NSDictionary *dic) {
//            [self.hud hideAnimated:YES];
//            if ([[dic objectForKey:@"status"] isEqualToString:@"SUCCESS"]) {
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    YOPushLiveViewController *pushLiveVC = [YOPushLiveViewController new];
//                    pushLiveVC.pushStreamUrl = dic[@"data"][@"pushStreamUrl"];
//                    pushLiveVC.chatRoomId = dic[@"data"][@"chatRoomId"];
//                    pushLiveVC.streamId = dic[@"data"][@"streamId"];
//                    [self presentViewController:pushLiveVC animated:YES completion:nil];
//                });
//            }
//        } withFailureBlock:^(NSError *error) {
//            [self.hud hideAnimated:YES];
//            [YOToast YOToastShow:@"请求超时!"];
//        }];
//    }else {
//        [YOToast YOToastShow:@"启动直播失败,请检查网络环境!"];
//    }
}

#pragma mark- TabBar Delegate
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tabBar.backgroundImage = [self imageWithColor:[UIColor colorWithRed:1 green:1 blue:1 alpha:1]];
    self.tabBar.shadowImage = [UIImage new];
    [self setTabBarVC];
//    [self setUp];
    [self setClassTabBar];
//    self.tabBar.backgroundImage = [UIImage imageNamed:@"tabbar_backimage"];
//    self.tabBar.selectedItem.imageInsets = UIEdgeInsetsMake(0, 0, 0, 0);
}

- (UIImage *)imageWithColor:(UIColor *)color {

    CGRect rect = CGRectMake(0.0f,0.0f, 1.0f,1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context =UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

// 初始化所有子控制器
- (void)setTabBarVC {
    [self setTabBarChildController:[[MHomeViewController alloc] init] title:@"口罩" image:@"home" selectImage:@"homeSelect"];
    [self setTabBarChildController:[[MControlViewController alloc]init] title:@"控制面板" image:@"control" selectImage:@"controlSelect"];
    [self setTabBarChildController:[[MDataCompartmentViewController alloc] init] title:@"数据舱" image:@"data" selectImage:@"dataSelect"];
    [self setTabBarChildController:[[MTaobaoViewController alloc] init] title:@"商店" image:@"taobao" selectImage:@"taobao"];
}

// 添加tabbar的子viewcontroller
- (void)setTabBarChildController:(UIViewController*)controller title:(NSString*)title image:(NSString*)imageStr selectImage:(NSString*)selectImageStr {
    BaseNavigationController* nav = [[BaseNavigationController alloc] initWithRootViewController:controller];
    nav.tabBarItem.title = title;
    //nav.tabBarController.view.backgroundColor = NAV_COLOR_RED;
    nav.tabBarItem.image = [[UIImage imageNamed:imageStr]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    nav.tabBarItem.selectedImage = [[UIImage imageNamed:selectImageStr]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [nav.tabBarItem setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13],NSForegroundColorAttributeName:[UIColor blackColor]} forState:UIControlStateNormal];
    [nav.tabBarItem setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13],NSForegroundColorAttributeName:[UIColor blackColor]} forState:UIControlStateSelected];
//    [nav.tabBarItem setTitlePositionAdjustment:UIOffsetMake(-4, -4)];
    [self addChildViewController:nav];
}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    for (UITabBarItem *item in self.tabBar.items) {
        [item setImageInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        //self.tabBar.selectedItem.imageInsets = UIEdgeInsetsMake(-12, 0, 12, 0);
    }
}

- (void)setClassTabBar {
    Class class = NSClassFromString(@"UITabBarButton");
    NSInteger btnIndex = 0;
    for (UIView *btn in self.tabBar.subviews) {//遍历tabbar的子控件
        if ([btn isKindOfClass:class]) {//如果是系统的UITabBarButton，那么就调整子控件位置，空出中间位置
            //按钮宽度为TabBar宽度减去中间按钮宽度的一半
            btn.width = self.tabBar.width / 5;
            //中间按钮前的宽度,这里就5个按钮，中间按钮Index为2
            if (btnIndex < 2) {
                btn.mj_x = btn.width * btnIndex;
            } else { //中间按钮后的宽度
                btn.mj_x = self.tabBar.width / 5 * 3;
            }
            
            btnIndex++;
            //如果是索引是0(从0开始的)，直接让索引++，目的就是让消息按钮的位置向右移动，空出来中间按钮的位置
            if (btnIndex == 0) {
                btnIndex++;
            }
        }
    }
    [self.tabBar bringSubviewToFront:tabBarButton];
}

// 动画
- (void)animationWithIndex:(NSInteger) index {
//    NSMutableArray * tabbarButtonArray = [NSMutableArray array];
//    for (UIView *button in self.tabBar.subviews) {
//        if ([button isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
//            [tabbarButtonArray addObject:button];
//        }
//    }
//    CABasicAnimation*pulse = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
//    pulse.timingFunction= [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
//    pulse.duration = 0.15;
//    pulse.repeatCount= 0;
//    pulse.autoreverses= YES;
//    pulse.fromValue= [NSNumber numberWithFloat:0.7];
//    pulse.toValue= [NSNumber numberWithFloat:1.3];
//    [[tabbarButtonArray[index] layer] addAnimation:pulse forKey:nil];
}

@end
